<!--
  - Copyright (c) 2021.  北京维数科技有限公司
  - Date :  2021/3/25
  - Author ：F12 Console=> atob("MzMxNDkxODAwQHFxLmNvbQ==")
  - Version ：1.0.0
  -->

<template>
  <SlidingPanel :Show="Show" :Width="Width" @update:Show="SlidingPanelHide" CustomClass="SlidingPanelContent">
    <!-- 自定义标题显示 -->
    <div class="actual-dialog-title">实时数据</div>
    <div class="sensor-realtime-status">
      <span>{{ sensorInfo.sensor }}<em
        style="font-style: normal;color:rgba(255, 255, 255, 0.7);font-size: 12px;">-{{
          sensorInfo.sensorNo
        }}</em></span>
      <span><icon-svg icon-class="building"
                      style="fill:rgba(80, 227, 194, 0.3);margin-right: 5px;"/>{{ sensorInfo.bName }}</span>
      <span><i class="el-icon-location"
               style="color:rgba(80, 227, 194, 0.3);margin-right: 5px;"></i>{{ sensorInfo.description }}</span>
      <span v-if="sensorInfo.status==='0'" class="sensor-status-abnormal" style="color:rgba(245, 166, 35, 0.7);"><icon-svg
        icon-class="status_icon_abnormal" style="fill:rgba(245, 166, 35, 0.7)"/>故障</span>
      <span v-if="sensorInfo.status==='1'" class="sensor-status-alram" style="color:rgba(219, 54, 29, 0.7)"><icon-svg
        icon-class="status_icon_warn" style="fill:rgba(219, 54, 29, 0.7)"/>报警</span>
      <span v-if="sensorInfo.status==='2'" class="sensor-status-normal" style="color:rgba(80, 227, 194, 0.3)"><icon-svg
        icon-class="status_icon_normal" style="fill: rgba(80, 227, 194, 0.3)"/>正常</span>
      <span v-if="sensorInfo.status==='4'" class="sensor-status-unline" style="color: rgba(248, 231, 28, 0.5)"><icon-svg
        icon-class="status_icon_offline" style="fill:rgba(248, 231, 28, 0.5)"/>离线</span>
    </div>
    <el-row>
      <el-row class="ac-header-wrap">
        <div class="ac-header-withtitle">
          <i class="el-icon-caret-right"></i>实时数据曲线88


          <v-show>
          </v-show>
            <div class="box-pie" id="main1" style="height: 400px;"  ref="chart"></div>


        </div>
        <div class="ac-header-icons">
          <span><icon-svg icon-class="baojing"/>报警</span>
          <span><icon-svg icon-class="jinggao" style="fill:#f5a623"/>故障</span>
          <span><icon-svg icon-class="jinzhi" style="fill:#6590ba"/>屏蔽</span>
        </div>
      </el-row>
      <el-row class="data-btn-left">
        <h2>时间</h2>
        <el-button-group>
          <el-button :type="datetype=='day'?'primary':''" @click="getDate('day')" size="mini">今日</el-button>
          <el-button :type="datetype=='yesterday'?'primary':''" @click="getDate('yesterday')" size="mini">昨日
          </el-button>
          <el-date-picker
            v-model="acrosstime"
            type="date"
            @change="selTime"
            placeholder="选择日期"
            value-format="yyyy-MM-dd"
            size="mini"
            :picker-options="pickerOptions"
          >
          </el-date-picker>
        </el-button-group>
      </el-row>
      <el-row class="data-btn-left">
        <h2>测点</h2>
        <el-button-group>
          <el-button size="mini" :type="ttype==item.codeName?'primary':''"
                     @click="selTemp(item.codeName,item.measuringPoint,item.dataUnit)" v-for="(item,index) in testtype"
                     :key="index">
            <span v-if="item.alarmStatus===1"><icon-svg icon-class="baojing"/></span>
            <span v-if="item.alarmStatus===0"><icon-svg icon-class="jinggao" style="fill:#f5a623"/></span>
            <span v-if="item.alarmStatus===3"><icon-svg icon-class="jinzhi" style="fill:#6590ba"/></span>
            {{ item.measuringPoint }}
          </el-button>
        </el-button-group>
      </el-row>
      <div class="fire-bot-chart">
        <div ref="dataTable" id="dataTable">
        </div>
        <div class="table-data-none" v-show="isnonedata">暂无数据</div>
      </div>
      <div class="history-record">
        <h2><i class="el-icon-caret-right"></i>历史记录</h2>
        <el-table key='tableKey' :data="list" v-loading="listLoading" fit style="width: 100%">
          <el-table-column label="测点">
            <template slot-scope="scope">
              <span>{{ scope.row.measuringPoint }}</span>
            </template>
          </el-table-column>
          <el-table-column label="报警类型">
            <template slot-scope="scope">
              <span>{{ scope.row.alrmType }}</span>
            </template>
          </el-table-column>
          <el-table-column label="报警时间">
            <template slot-scope="scope">
              <span>{{ scope.row.alrmDate }}</span>
            </template>
          </el-table-column>
          <el-table-column label="处理人">
            <template slot-scope="scope">
              <span>{{ scope.row.confirPerson }}</span>
            </template>
          </el-table-column>
          <el-table-column label="处理时间">
            <template slot-scope="scope">
              <span>{{ scope.row.confirDate }}</span>
            </template>
          </el-table-column>
          <el-table-column label="真实火警">
            <template slot-scope="scope">
								<span v-if="scope.row.fireFlag==='1'">
									是
								</span>
              <span v-if="scope.row.fireFlag==='0'||scope.row.fireFlag==='2'">
									否
								</span>
            </template>
          </el-table-column>
        </el-table>
        <div v-show="!listLoading" class="pagination-container">
          <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                         :current-page.sync="listQuery.page" :page-sizes="[5,10,15,30]" :page-size="listQuery.limit"
                         layout="total, sizes, prev, pager, next, jumper" :total="total"></el-pagination>
        </div>
      </div>
    </el-row>
  </SlidingPanel>
</template>
<script>
import SlidingPanel from '@/components/SliderPanel'
import {
  getrealTime,
  getTestType,
  pageRecord,
  sensorInfo
} from "@/api/device/deviceBuilding/index";
import echarts from 'echarts'

export default {
  name: 'actualData',
  components: {SlidingPanel},
  props: {
    Show: {required: true, default: false},
    Width: {type: Number, default: 980},
    sensorid: {
      default: ""
    },
    attr2: {
      default: ""
    },
    sensornum: {
      default: ""
    },
    sensortype: {
      default: ""
    }
  },
  data() {
    return {
      option: {
        xAxis: {
          type: 'category',
          data: []
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            data: [],
            type: 'line',
            smooth: true
          }
        ]
      },
      myChart: null,
      wsUrl: 'ws://localhost:8888/ws/cnm', // ws地址
      // /Url: "ws://localhost:2345/alarm/websocket?userId=1 ",
      // ws地址
      websock: null, // ws实例
      tableKey: 0,
      listLoading: false,
      sensorInfo: {},
      list: [],
      listQuery: {
        page: 1,
        limit: 5,
        sensorId: undefined,
      },
      total: 0,
      query: {
        mac: "f01c29",//设备编号
        sensorType: "",
        startTime: "2021-05-18",
        endTime: "2021-12-30",
      },
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now() - 8.64e6
        }
      },
      datetype: "",
      acrosstime: "",
      xAxisdata: [],
      yAxisdata: [],
      testtype: [],
      ttype: "",
      seltype: {},
      measurename: "",
      dataUnit: "",
      isnonedata: false,
    }
  },
  mounted() {
    //初始化表格
    this.initEcharts();
    this.initWebSocket();//初始化websocket
  },
  destroyed() {
    // 离开路由之后断开websocket连接
    this.websock.close()
  },
  methods: {
    // 初始化weosocket
    initWebSocket() {
      if (typeof WebSocket === 'undefined')
        return console.log('您的浏览器不支持websocket')
      this.websock = new WebSocket(this.wsUrl)
      this.websock.onmessage = this.websocketonmessage
      this.websock.onopen = this.websocketonopen
      this.websock.onerror = this.websocketonerror
      this.websock.onclose = this.websocketclose
    },
    websocketonopen() {
      // 连接建立之后执行send方法发送数据
      let actions = {test: 'test'}
      this.websocketsend(JSON.stringify(actions))
    },
    websocketonerror() {
      // 连接建立失败重连
      this.initWebSocket()
    },
    websocketonmessage(e) {
      // 数据接收
      const redata = e.data
      console.log('接收的数据', redata)//d
      if (this.option.series[0].data.length == 24) {
        this.option.series[0].data.shift() //删除第一个元素
      }
      if (this.option.xAxis.data.length == 24) {
        this.option.xAxis.data.shift();
      }
      this.option.xAxis.data.push(this.getCurrentTime())
      this.option.series[0].data.push(redata) //往图形报表中的数组添加元素
      this.initEcharts();
    },
    websocketsend(Data) {
      // 数据发送
      this.websock.send(Data)
    },
    websocketclose(e) {
      // 关闭
      console.log('断开连接', e)
    },

    initEcharts() {
      var elementById = document.getElementById("main1");
      this.myChart = this.$echarts.init(elementById);
      this.myChart.setOption(this.option);
    },
    getCurrentTime() {
      var date = new Date();//当前时间
      var year = date.getFullYear() //返回指定日期的年份
      var month = this.repair(date.getMonth() + 1);//月
      var day = this.repair(date.getDate());//日
      var hour = this.repair(date.getHours());//时
      var minute = this.repair(date.getMinutes());//分
      var second = this.repair(date.getSeconds());//秒

      //当前时间
      var curTime = year + "-" + month + "-" + day
        + " " + hour + ":" + minute + ":" + second;
      return curTime;
    },
    repair(i) {
      if (i >= 0 && i <= 9) {
        return "0" + i;
      } else {
        return i;
      }
    },
    getList() {
      // 异常记录表的接口
      this.listLoading = true;
      this.listQuery.sensorId = this.sensorid;
      pageRecord(this.listQuery).then(response => {
        this.list = response.data.rows;
        this.total = response.data.total;
        this.listLoading = false;
      }).catch(() => {
        this.listLoading = false;
      })
    },
    getSensorInfo() {
      传感器信息接口
      sensorInfo({id: this.sensorid}).then(res => {
        this.sensorInfo = res.data;
      }).catch(() => {

      })
    },
    handleSizeChange(val) {
      this.listQuery.limit = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.page = val;
      this.getList();
    },
    formatDate(date) {
      let myyear = date.getFullYear();
      let mymonth = date.getMonth() + 1;
      let myweekday = date.getDate();
      if (mymonth < 10) {
        mymonth = "0" + mymonth;
      }
      if (myweekday < 10) {
        myweekday = "0" + myweekday;
      }
      return (myyear + "-" + mymonth + "-" + myweekday);
    },
    getToday() {//获取当天日期
      let date = new Date();
      let seperator1 = "-";
      let year = date.getFullYear();
      let month = date.getMonth() + 1;
      let strDate = date.getDate();
      if (month >= 1 && month <= 9) {
        month = "0" + month;
      }
      if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
      }
      let currentdate = year + seperator1 + month + seperator1 + strDate;
      this.query.startTime = currentdate;
      this.query.endTime = currentdate;
    },
    getYesterday() {
      // 获取昨天日期
      const date = new Date();
      date.setTime(date.getTime() - 3600 * 1000 * 24);
      let currentdate = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();
      this.query.startTime = currentdate;
      this.query.endTime = currentdate;
    },
    selTemp(type, mname, dataUnit) {
      this.ttype = type;
      this.measurename = mname;
      this.dataUnit = dataUnit;
      this.query.sensorType = type;
      this.getrealtime();
    },
    firstselTemp(type, mname, dataUnit) {
      this.ttype = type;
      this.measurename = mname;
      this.dataUnit = dataUnit;
      this.query.sensorType = type;
    },
    getDate(date) {
      this.datetype = date;
      this.acrosstime = "";
      switch (date) {
        case 'day':
          this.getToday();
          break;
        case 'yesterday':
          this.getYesterday();
          break;
      }
      this.getrealtime();
    },
    selTime(val) {
      this.datetype = "";

      this.query.startTime = val;
      this.query.endTime = val;
      this.getrealtime();
    },
    getrealtime() {
      let self = this;
      getrealTime(Object.assign({}, this.query, this.seltype, {channelId: this.attr2})).then(res => {
        self.xAxisdata = [];
        self.yAxisdata = [];
        res.forEach(function (item, index) {
          self.xAxisdata.push(item.inputdate);
          self.yAxisdata.push(item.temperature)
        });
        return res;
      }).then((res) => {
        if (res.length == 0) {
          self.isnonedata = true;
        } else {
          self.isnonedata = false;
        }
        self.initChart2(self.xAxisdata, self.yAxisdata, self.measurename, self.dataUnit)
      })
    },
    resetdata() {
      this.query.mac = this.sensornum;//设备编号
      this.query.sensorType = "";
      this.query.startTime = "";
      this.query.endTime = "";
      this.seltype = {};
    },
    SlidingPanelHide(v) {
      this.$emit('update:Show', v)
    },
    initChart2(x, y, n, du) {
      let chart = echarts.init(document.getElementById('dataTable'));
      let option = {
        title: {
          text: ''
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: 'line',
            snap: true,
            label: {
              backgroundColor: '#6a7985'
            }
          },
          formatter: function (params, ticket, callback) {
            let data = params[0];
            return data.seriesName + ":" + data.value + "<br>" + data.marker + data.name;
          }
        },
        grid: {
          left: '4%',
        },
        dataZoom: [
          {
            type: 'inside',
            start: 0,
            end: 100
          },
        ],
        xAxis: [
          {
            type: 'category',
            boundaryGap: false,
            data: x,
            axisLine: {
              show: false,
              lineStyle: {
                color: "rgba(80, 227, 194, 0.3)"
              }
            }
          }
        ],
        yAxis: [
          {
            name: '单位：' + du,
            type: 'value',
            axisLine: {
              show: false,
              lineStyle: {
                color: "rgba(80, 227, 194, 0.3)"
              }
            },
            splitLine: {
              show: true,
              lineStyle: {
                color: 'rgba(80, 227, 194, 0.7)'
              }
            }
          }
        ],
        series: [
          {
            name: n,
            type: 'line',
            showAllSymbol: false,
            smooth: true,
            sampling: 'average',
            stack: '总量',
            itemStyle: {
              normal: {
                color: '#50E3C2',
                label: {
                  show: true
                }
              }
            },
            areaStyle: {
              normal: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                  offset: 0,
                  color: 'rgba(136, 243, 227, 0.7)'
                }, {
                  offset: 1,
                  color: 'rgba(0,0,0,0)'
                }])
              }
            },
            data: y
          }
        ]
      };
      chart.setOption(option);
    },
    // rendertable() {
    //   this.initChart2()
    // }
  },
  watch: {
    Show: function (val) {
      let self = this;
      if (val) {
        this.$nextTick(function () {
          self.resetdata();
          self.query.mac = self.sensornum;
          self.getSensorInfo();
          self.getList();
          getTestType(self.sensorid, {channelId: self.attr2}).then(res => {
            self.testtype = res;
            self.firstselTemp(res[0].codeName, res[0].measuringPoint, res[0].dataUnit);
          }).then(() => {
            self.xAxisdata = [];
            self.yAxisdata = [];
            self.getDate('day');
          })
        })
      }
    }
  }
}
</script>
<style lang="scss">
.actual-dialog-title {
  font-size: 24px;
  color: #50E3C2;
  width: 185px;
  padding-bottom: 20px;
}

.fire-data-btngroup {
  display: flex;
  justify-content: space-between;
  margin-top: 63px;
}

#dataTable {
  width: 100%;
  height: 290px;
}
.box-pie{
  width: 400%;
  height: 290px;
  background: #fff;
  border-radius: 10px;
  padding: 20px;
  box-sizing: border-box;
  margin-bottom: 20px;
}
</style>
